//
//  BMSPopupManager.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

// BMSPopupQueueManager.m
// BMSPopupQueueManager.m
#import "BMSPopupQueueManager.h"
#import <Masonry/Masonry.h>

@interface BMSPopupQueueManager ()
@property (nonatomic, strong) UIView *currentMaskView;
@property (nonatomic, strong) UIView *currentPopupContainer;
@property (nonatomic, strong) UIView *currentPopupContent;
@property (nonatomic, copy) NSString *currentPopupName;
@property (nonatomic, strong) NSMutableArray<NSDictionary<NSString *, id> *> *popupQueue;
@property (nonatomic, assign) BOOL isPresenting;
@end

@implementation BMSPopupQueueManager

+ (instancetype)sharedManager {
    static BMSPopupQueueManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.popupQueue = [NSMutableArray array];
    });
    return instance;
}

- (void)presentPopup:(UIView *)popupView {
    [self presentPopup:popupView withName:nil];
}

- (void)presentPopup:(UIView *)popupView withName:(nullable NSString *)popupName {
    if (!popupView) return;

    void (^presentationBlock)(void) = ^{
        NSLog(@"[BMSPopupQueue] Present popup: %@", popupName ?: NSStringFromClass(popupView.class));
        self.isPresenting = YES;
        self.currentPopupContent = popupView;
        self.currentPopupName = popupName ?: NSStringFromClass(popupView.class);

        UIView *window = UIApplication.sharedApplication.windows.firstObject;
        if (!window) return;

        self.currentMaskView = [[UIView alloc] initWithFrame:window.bounds];
        self.currentMaskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        self.currentMaskView.userInteractionEnabled = YES;
        self.currentMaskView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [window addSubview:self.currentMaskView];

        // 弹窗容器
        UIView *popupContainer = [[UIView alloc] init];
        popupContainer.userInteractionEnabled = YES;
        popupContainer.backgroundColor = UIColor.clearColor;
        popupContainer.translatesAutoresizingMaskIntoConstraints = NO;
        [self.currentMaskView addSubview:popupContainer];
        self.currentPopupContainer = popupContainer;

        [popupContainer addSubview:popupView];
        popupView.userInteractionEnabled = YES;

        [popupContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.currentMaskView);
            make.width.greaterThanOrEqualTo(@280);
            make.width.lessThanOrEqualTo(self.currentMaskView).multipliedBy(0.9);
            make.width.lessThanOrEqualTo(@400);
            make.height.lessThanOrEqualTo(self.currentMaskView).multipliedBy(0.95);
        }];

        [popupView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(popupContainer);
        }];

        popupContainer.transform = CGAffineTransformMakeScale(0.8, 0.8);
        popupContainer.alpha = 1;
        [UIView animateWithDuration:0.25 animations:^{
            popupContainer.alpha = 1.0;
            popupContainer.transform = CGAffineTransformIdentity;
        }];
    };

    if (self.isPresenting) {
        NSLog(@"[BMSPopupQueue] Queued popup: %@", popupName ?: NSStringFromClass(popupView.class));
        [self.popupQueue addObject:@{ @"name": popupName ?: NSStringFromClass(popupView.class), @"block": [presentationBlock copy] }];
    } else {
        presentationBlock();
    }
}

- (void)dismissCurrentPopup {
    [self dismissCurrentPopupWithCompletion:nil];
}

- (void)dismissCurrentPopupWithCompletion:(void (^)(void))completion {
    if (!self.currentPopupContainer) {
        if (completion) completion();
        return;
    }

    NSLog(@"[BMSPopupQueue] Dismiss popup: %@", self.currentPopupName ?: NSStringFromClass(self.currentPopupContent.class));
    [UIView animateWithDuration:0.2 animations:^{
        self.currentPopupContainer.alpha = 0.0;
        self.currentMaskView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self.currentPopupContainer removeFromSuperview];
        [self.currentMaskView removeFromSuperview];
        self.currentPopupContainer = nil;
        self.currentPopupContent = nil;
        self.currentMaskView = nil;
        self.currentPopupName = nil;
        self.isPresenting = NO;
        if (completion) completion();
        [self tryDequeue];
    }];
}

- (void)dismissCurrentPopupImmediately {
    NSLog(@"[BMSPopupQueue] Immediate dismiss popup: %@", self.currentPopupName ?: NSStringFromClass(self.currentPopupContent.class));
    [self.currentPopupContainer removeFromSuperview];
    [self.currentMaskView removeFromSuperview];
    self.currentPopupContainer = nil;
    self.currentPopupContent = nil;
    self.currentMaskView = nil;
    self.currentPopupName = nil;
    self.isPresenting = NO;
    [self tryDequeue];
}

- (void)tryDequeue {
    if (self.popupQueue.count == 0) {
        NSLog(@"[BMSPopupQueue] Queue empty");
        return;
    }
    NSDictionary *next = [self.popupQueue firstObject];
    [self.popupQueue removeObjectAtIndex:0];
    void (^nextBlock)(void) = next[@"block"];
    NSLog(@"[BMSPopupQueue] Dequeue and present popup: %@", next[@"name"]);
    dispatch_async(dispatch_get_main_queue(), ^{
        nextBlock();
    });
}



@end
